package com.zhentao.camera.service;

import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import org.springframework.stereotype.Service;
import java.util.concurrent.atomic.AtomicBoolean;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

@Service
public class CameraService {
    private OpenCVFrameGrabber grabber;
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private static final String PHOTO_PATH = "C:\\Users\\15134\\Desktop\\壁纸\\";
    
    public void startCamera(int deviceId) throws Exception {
        if (isRunning.get()) {
            throw new IllegalStateException("相机已经在运行中");
        }
        
        try {
            grabber = new OpenCVFrameGrabber(deviceId);
            // 设置摄像头参数
            grabber.setImageWidth(640);
            grabber.setImageHeight(480);
            grabber.setFrameRate(30);
            
            // 初始化并启动
            grabber.start();
            isRunning.set(true);
        } catch (Exception e) {
            if (grabber != null) {
                try {
                    grabber.release();
                } catch (Exception ex) {
                    // 忽略释放时的错误
                }
            }
            throw new RuntimeException("无法启动摄像头，请确保摄像头已正确连接: " + e.getMessage());
        }
    }
    
    public Frame grabFrame() throws Exception {
        if (!isRunning.get() || grabber == null) {
            throw new IllegalStateException("相机未启动");
        }
        try {
            return grabber.grab();
        } catch (Exception e) {
            stopCamera();
            throw new RuntimeException("获取视频帧失败: " + e.getMessage());
        }
    }
    
    public void stopCamera() throws Exception {
        if (isRunning.get() && grabber != null) {
            isRunning.set(false);
            try {
                grabber.stop();
                grabber.release();
            } finally {
                grabber = null;
            }
        }
    }
    
    public boolean isRunning() {
        return isRunning.get();
    }
    
    public String takePhoto() throws Exception {
        if (!isRunning.get() || grabber == null) {
            throw new IllegalStateException("相机未启动");
        }
        
        try {
            Frame frame = grabber.grab();
            if (frame == null) {
                throw new RuntimeException("无法获取图像");
            }
            
            // 转换Frame为BufferedImage
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bufferedImage = converter.getBufferedImage(frame);
            
            // 生成文件名（使用时间戳）
            String fileName = "photo_" + System.currentTimeMillis() + ".jpg";
            String fullPath = PHOTO_PATH + fileName;
            
            // 确保目录存在
            File directory = new File(PHOTO_PATH);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存图片
            File outputFile = new File(fullPath);
            ImageIO.write(bufferedImage, "jpg", outputFile);
            
            return fileName;
        } catch (Exception e) {
            throw new RuntimeException("拍照失败: " + e.getMessage());
        }
    }
}
